package com.yami.shop.common.util.baidu.face;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yami.shop.common.exception.FaceCompareErrorException;
import com.yami.shop.common.util.Json;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;

/**
 * 人脸对比
 * https://ai.baidu.com/ai-doc/FACE/Lk37c1tpf
 */
@Slf4j
public class FaceCompare {

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     * <p>
     * <p>
     * 人脸相似度得分，推荐阈值80分
     * {
     * "error_code": 0,
     * "error_msg": "SUCCESS",
     * "log_id": 9494552584799,
     * "timestamp": 1626086555,
     * "cached": 0,
     * "result":
     * {
     * "score": 97.64893341,
     * "face_list":
     * [
     * {
     * "face_token": "fc82abcb2cc27685f2cb26bf639490ed"
     * },
     * {
     * "face_token": "403456ca3e874fa1223130a2b21787be"
     * }
     * ]
     * }
     * }
     */
    /**
     * URL图片人脸比对
     * @param pic1
     * @param pic2
     * @return true本人验证通过
     * @throws Exception
     */
    public static boolean faceCompare(String pic1, String pic2) throws Exception {
        Assert.notBlank(pic1,"提交图片不得为空");
        Assert.notBlank(pic2,"用户注册人脸图片不得为空");
        //人脸对比
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";

        ArrayList<CompareMap> map = new ArrayList<>();
        map.add(new CompareMap(pic1, "URL"));
        map.add(new CompareMap(pic2, "URL"));
        String param = GsonUtils.toJson(map);

        // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
        String accessToken = AuthService.getAuth();

        String result = HttpUtil.post(url, accessToken, "application/json", param);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (!jsonObject.get("error_code").equals(0)) {
            log.error("人脸比对失败\n"+JSONUtil.formatJsonStr(result));
            throw new FaceCompareErrorException(result);
        }
        if ((double) jsonObject.getByPath("result.score") > 80) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        boolean b = false;
        try {
            b = FaceCompare.faceCompare("http://xiuqiu.xiuqiu.cc/1.jpg",
                    "http://xiuqiu.xiuqiu.cc/2.jpg");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println(b);
    }
}
